﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using FileHelpers;
using System.Data;

namespace FlexiPay
{
    public partial class DataUpload : System.Web.UI.Page
    {
        #region init members
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                manageButtons("Page_Load");
                manageDisplayTabs();
                manageGrids();
            }
        }

        private void manageButtons(string source)
        {
            if (source == "ViewData")
            {
                TableListDropDown.Enabled = false;
                SeperatorDDL.Enabled = false;
                FileUpload1.Enabled = false;
                ButtonViewData.Enabled = false;
                UploadButton.Enabled = true;
                ResetButton.Enabled = true;
            }
            else if (source == "Page_Load")
            {
                UploadButton.Enabled = false;
                ResetButton.Enabled = false;
                ErrorButton.Enabled = false;
            }
            else if (source == "Reset")
            {
                TableListDropDown.Enabled = true;
                SeperatorDDL.Enabled = true;
                FileUpload1.Enabled = true;
                ButtonViewData.Enabled = true;
                ErrorButton.Enabled = false;
                UploadButton.Enabled = false;
                ResetButton.Enabled = false;
            }
            return;
        }

        protected void manageDisplayTabs()
        {
            String tableName = DataUploadVariables.Table4DataUpload;

            //manage tabs
            TabData_Sales.Enabled = tableName.Equals("CarSalesData");
            TabReject_Sales.Enabled = tableName.Equals("CarSalesData");
            TabCityCategory.Enabled = tableName.Equals("CityCategory");
            TabDMAMaster.Enabled = tableName.Equals("DMAMaster");
            TabSegment.Enabled = tableName.Equals("Segments");
            TabSource.Enabled = tableName.Equals("Source");
            TabGenTable.Enabled = DataUploadVariables.GenTableList.Contains(tableName);


            //manage header text
            TabData_Sales.HeaderText = tableName.Equals("CarSalesData") ? "Upload Data" : String.Empty;
            TabReject_Sales.HeaderText = tableName.Equals("CarSalesData") ? "Rejected Data" : String.Empty;
            TabCityCategory.HeaderText = tableName.Equals("CityCategory") ? "Upload Data" : String.Empty;
            TabDMAMaster.HeaderText = tableName.Equals("DMAMaster") ? "Upload Data" : String.Empty;
            TabSegment.HeaderText = tableName.Equals("Segments") ? "Upload Data" : String.Empty;
            TabSource.HeaderText = tableName.Equals("Source") ? "Upload Data" : String.Empty;
            TabGenTable.HeaderText = DataUploadVariables.GenTableList.Contains(tableName) ? "Upload Data" : String.Empty;

            return;
        }

        protected void manageGrids()
        {
            String tableName = DataUploadVariables.Table4DataUpload;
            // error data
            JQGridErrors.DataSource = DataUploadVariables.ErrorData;
            JQGridErrors.DataBind();
            // sales data
            JQGridSalesInput.DataSource = tableName.Equals("CarSalesData") ? DataUploadVariables.UploadData : null;
            JQGridSalesInput.DataBind();
            JQGridSalesRejected.DataSource = tableName.Equals("CarSalesData") ? DataUploadVariables.RejectedData : null;
            JQGridSalesRejected.DataBind();
            // city category
            JQGridCityCatInput.DataSource = tableName.Equals("CityCategory") ? DataUploadVariables.UploadData : null;
            JQGridCityCatInput.DataBind();
            //DMA Master
            JQGridDMAMaster.DataSource = tableName.Equals("DMAMaster") ? DataUploadVariables.UploadData : null;
            JQGridDMAMaster.DataBind();
            //Segment
            JQGridSegment.DataSource = tableName.Equals("Segments") ? DataUploadVariables.UploadData : null;
            JQGridSegment.DataBind();
            //Generic Tables = { "Employers", "SchemeCode", "PromotionScheme", "ChannelCode", "MOP" }
            JQGridGenTable.DataSource = DataUploadVariables.GenTableList.Contains(tableName) ? DataUploadVariables.UploadData : null;
            JQGridGenTable.DataBind();
            //Source
            JQGridSource.DataSource = tableName.Equals("Source") ? DataUploadVariables.UploadData : null;
            JQGridSource.DataBind();
        }
        #endregion

        #region buttons at work
        protected void ButtonViewData_Click(object sender, EventArgs e)
        {
            if (!FileUpload1.HasFile) return;
            retrieveData();
            manageButtons("ViewData");
            manageDisplayTabs();
        }

        protected void ErrorButton_Click(object sender, EventArgs e)
        {
            if (DataUploadVariables.ErrorData != null)
            {
                Response.ContentType = "Error File (*.txt)";
                Response.AppendHeader("Content-Disposition", "attachment; filename=errors.txt");
                Response.TransmitFile(Server.MapPath("~\\errors.txt"));
                Response.End();
            }
        }

        protected void UploadButton_Click(object sender, EventArgs e)
        {
            string errorText = " Upload Success.";
            try
            {
                if (DataUploadVariables.Table4DataUpload == "CarSalesData")
                {
                    //save unbilled entries
                    if (DataUploadVariables.UploadData != null)
                    {
                        //DataColumn status = new DataColumn();
                        DataUploadVariables.UploadData.Columns.Add("EntryStatus", typeof(String), "'Unbilled'");
                        DataUploadVariables.UploadData.Columns.Add("CretedBy", typeof(String), "'" + GlobalVariables.loginId + "'");
                        DataUploadVariables.UploadData.Columns.Add("CreatedOn", typeof(DateTime), "'" + System.DateTime.Now.ToString() + "'");
                        DataBaseMethods.uploadDT2DB(DataUploadVariables.UploadData, DataUploadVariables.Table4DataUpload);
                    }

                    //and also save rejected entries
                    if (DataUploadVariables.RejectedData != null)
                    {
                        DataUploadVariables.RejectedData.Columns.Add("EntryStatus", typeof(String), "'Rejected'");
                        DataUploadVariables.RejectedData.Columns.Add("CretedBy", typeof(String), "'" + GlobalVariables.loginId + "'");
                        DataUploadVariables.RejectedData.Columns.Add("CreatedOn", typeof(DateTime), "'" + System.DateTime.Now.ToString() + "'");
                        DataBaseMethods.uploadDT2DB(DataUploadVariables.RejectedData, DataUploadVariables.Table4DataUpload,false);
                    }
                }
                else if ((DataUploadVariables.Table4DataUpload == "CityCategory")
                    || (DataUploadVariables.Table4DataUpload == "Segments") || (DataUploadVariables.Table4DataUpload == "Source"))
                {
                    if (DataUploadVariables.UploadData != null)
                    {
                        DataUploadVariables.UploadData.Columns.Add("CretedBy", typeof(String), "'" + GlobalVariables.loginId + "'");
                        DataUploadVariables.UploadData.Columns.Add("CreatedOn", typeof(DateTime), "'" + System.DateTime.Now.ToString() + "'");
                        DataBaseMethods.uploadDT2DB(DataUploadVariables.UploadData, DataUploadVariables.Table4DataUpload,true);
                    }
                }
                else if ((DataUploadVariables.Table4DataUpload == "DMAMaster"))
                {
                    if (DataUploadVariables.UploadData != null)
                    {
                        DataUploadVariables.UploadData.Columns.Add("CretedBy", typeof(String), "'" + GlobalVariables.loginId + "'");
                        DataUploadVariables.UploadData.Columns.Add("CreatedOn", typeof(DateTime), "'" + System.DateTime.Now.ToString() + "'");
                        DataBaseMethods.uploadDT2DB(DataUploadVariables.UploadData, DataUploadVariables.Table4DataUpload,false);
                    }
                }

                else if (DataUploadVariables.GenTableList.Contains(DataUploadVariables.Table4DataUpload))
                {
                    if (DataUploadVariables.UploadData != null)
                    {
                        DataUploadVariables.UploadData.Columns.Add("Category", typeof(String), "'GenTable'");
                        DataUploadVariables.UploadData.Columns["Category"].SetOrdinal(0);
                        DataUploadVariables.UploadData.Columns.Add("Name", typeof(String), "'" + DataUploadVariables.Table4DataUpload + "'");
                        DataUploadVariables.UploadData.Columns["Name"].SetOrdinal(1);
                        DataUploadVariables.UploadData.Columns.Add("CretedBy", typeof(String), "'" + GlobalVariables.loginId + "'");
                        DataUploadVariables.UploadData.Columns.Add("CreatedOn", typeof(DateTime), "'" + System.DateTime.Now.ToString() + "'");
                        DataBaseMethods.uploadDT2DB(DataUploadVariables.UploadData, "GenericTable", true);
                    }
                }
                else
                {
                    throw new Exception("No Upload Definition Defined for this table.");
                }
            }
            catch (Exception exception)
            {
                errorText += "\n Following error occured while uploading the data:\n " + exception.Message;
                //errorText += " Ignoring Existing entries.";
            }
            Logger.Show(errorText);
            ResetButton_Click(sender, e);
        }

        protected void ResetButton_Click(object sender, EventArgs e)
        {
            manageButtons("Reset");
            manageDisplayTabs();

            //set all others to null;
            DataUploadVariables.UploadData = null;
            DataUploadVariables.RejectedData = null;
            DataUploadVariables.ErrorData = null;
            manageGrids();

            return;
        }
        #endregion

        #region data operations
        private void retrieveData()
        {
            retrieveFileAsDataTable(FileUpload1.PostedFile);

            if (DataUploadVariables.fileEngine.ErrorManager.HasErrors)
                generateErrorDataTable();
            //checkRejectedData();
        }

        void checkRejectedData()
        {
            //get list of city codes
            string query = "select [CityCode] from [StateCity] ";
            DataTable citylist = DataBaseMethods.ExecuteSelectQuery(query);

            //get invalid enties
            var banned = from row in DataUploadVariables.UploadData.AsEnumerable()
                         join city in citylist.AsEnumerable() on row.Field<string>("CityCode")
                         equals city.Field<string>("CityCode")
                         into j
                         from x in j.DefaultIfEmpty()
                         where x == null
                         select row;
            DataUploadVariables.RejectedData = banned.CopyToDataTable<DataRow>();

            //get valid entries
            var exceptBanned = from row in DataUploadVariables.UploadData.AsEnumerable()
                               join city in citylist.AsEnumerable() on row.Field<string>("CityCode")
                               equals city.Field<string>("CityCode")
                               into j
                               from x in j.DefaultIfEmpty()
                               where x != null
                               select row;
            DataUploadVariables.UploadData = exceptBanned.CopyToDataTable<DataRow>();
        }

        void retrieveFileAsDataTable(HttpPostedFile fileStream)
        {
            //initial setup
            TextReader tr = new StreamReader(fileStream.InputStream);
            DataUploadVariables.fileEngine.Options.Delimiter = this.SeperatorDDL.SelectedValue;
            DataUploadVariables.fileEngine.Options.IgnoreFirstLines = 1;
            //DataUploadVariables.fileEngine.Options.RecordCondition.Condition = RecordCondition.IncludeIfMatchRegex(
            DataUploadVariables.fileEngine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;

            //read the file
            DataUploadVariables.UploadData = DataUploadVariables.fileEngine.ReadStreamAsDT(tr);
            DataUploadVariables.fileEngine.ErrorManager.SaveErrors(Server.MapPath("~\\errors.txt"));
        }

        void generateErrorDataTable()
        {
            DataUploadVariables.ErrorData = new DataTable();
            ErrorButton.Enabled = true;
            DataUploadVariables.ErrorData.Columns.Add("LineNumber");
            DataUploadVariables.ErrorData.Columns.Add("LineString");
            DataUploadVariables.ErrorData.Columns.Add("ErrorDescription");
            DataUploadVariables.ErrorData.AcceptChanges();

            foreach (ErrorInfo err in DataUploadVariables.fileEngine.ErrorManager.Errors)
            {
                DataRow dr = DataUploadVariables.ErrorData.NewRow();
                dr[0] = err.LineNumber.ToString();
                dr[1] = err.RecordString;
                dr[2] = err.ExceptionInfo.Message;
                DataUploadVariables.ErrorData.Rows.Add(dr);
            }
            DataUploadVariables.ErrorData.AcceptChanges();
        }
        #endregion

        #region jqgrid display & table store
        protected void JQGrid_DataRequesting(object sender, Trirand.Web.UI.WebControls.JQGridDataRequestEventArgs e)
        {
            manageGrids();
        }
        //manage the fileEngine & JQGrids on the basis of selected value
        protected void TableListDropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataUploadVariables.Table4DataUpload = TableListDropDown.SelectedValue;
            manageDisplayTabs();
        }

        protected void TableListDropDown_DataBound(object sender, EventArgs e)
        {
            TableListDropDown.SelectedValue = DataUploadVariables.Table4DataUpload;
        }
        #endregion
    }
}